// app.js
App({
  data: {
    // 用户登录缓存key
    cache_user_login_key: "cache_user_login_key",

    // 用户信息缓存key
    cache_user_info_key: "cache_shop_user_info_key",

    cache_user_info: "cache_user_info",

    // 用户站点信息缓存key
    cache_user_merchant_key: "cache_shop_user_merchant_key",

    // 设备信息缓存key
    cache_system_info_key: "cache_shop_system_info_key",

    // 用户地址选择缓存key
    cache_buy_user_address_select_key: "cache_buy_user_address_select_key",

    // 启动参数缓存key
    cache_launch_info_key: "cache_shop_launch_info_key",

    // 默认用户头像
    default_user_head_src: "/images/default-user.png",

    // 成功圆形提示图片
    default_round_success_icon: "/images/default-round-success-icon.png",

    // 错误圆形提示图片
    default_round_error_icon: "/images/default-round-error-icon.png",

    request_url: "https://hmb-app.bbg.com.cn/",//正式环境

    // request_url: "https://hmb-img.bbg.com.cn/", //测试

    // 价格符号
    price_symbol: "￥",

    //领取赠送券
    get_gif_url: 'get_gif_url',
    get_gif_parme: 'get_gif_parme',
    get_gif_status: 'get_gif_status',
    get_notshared_gift: 'get_notshared_gift'
    // get_gift_coupons: 'get_gift_coupons'
    // wx.getStorageSync('get_gift_coupons')
  },
  onLaunch() {
    let windowInfo = wx.getWindowInfo();
    let deInfo = wx.getDeviceInfo();
    var jl = wx.getMenuButtonBoundingClientRect();
    this.globalData.isWindows = deInfo.system.indexOf("Windows") >= 0 ? true : false;
    this.globalData.sw = windowInfo.screenWidth;
    this.globalData.sh = windowInfo.screenHeight;
    this.globalData.jlTop = jl.top;
    this.globalData.jlHeight = jl.height;
    this.globalData.winHeight = windowInfo.windowHeight;
    const userInfo = wx.getStorageSync('userInfo');
    this.globalData.userInfo = (userInfo === null || userInfo === "" || userInfo === "undefined") ? null : userInfo;
    let rate = 750 / windowInfo.screenWidth;
    let jltop = jl.top;
    let ntt = (jltop + 5) * rate;
    this.globalData.tittop = ntt;
    let jlheight = jl.height;
    let lt = this.globalData.isWindows ? 0 : (jltop + jlheight + 10) * rate;
    this.globalData.lbtop = lt;

    //获取更新管理器实例
    const updateManager = wx.getUpdateManager();
    //监听向微信后台i请求检查更新结果事件
    updateManager.onCheckForUpdate(function (res) {
      // 请求完新版本信息的回调
      if (res.hasUpdate) {
        console.log('发现新版本，正在下载...');
      } else {
        console.log('当前已是最新版本');
      }
    });
    // 监听新版本下载完成事件
    updateManager.onUpdateReady(function () {
      console.log("更新11111")
      // 新版本下载完成，提示用户重启
      wx.showModal({
        title: '更新提示',
        content: '新版本已经准备好，是否重启应用？',
        confirmText: '重启',
        cancelText: '稍后',
        success: function (res) {
          if (res.confirm) {
            console.log('用户确认更新，即将重启');
            updateManager.applyUpdate();
          }
        },
        fail: function (err) {
          console.error('显示更新提示模态框失败:', err);
          // 如果显示模态框失败，也可以尝试直接应用更新（谨慎使用）
          // updateManager.applyUpdate();
        }
      });
    });

    // 监听新版本下载失败事件
    updateManager.onUpdateFailed(function () {
      console.log('新版本下载失败');
      // 可以给用户一个提示，告知更新失败，稍后重试
      wx.showToast({
        title: '更新失败',
        icon: 'none',
        duration: 2000
      });
    });



  },
  globalData: {
    userInfo: null,
    sw: 0,
    sh: 0,
    isWindows: false,
    jlTop: 0,
    jlHeight: 32,
    winHeight: 0,
    tittop: 80,
    lbtop: 15,
    rcode: '',
    isFirst: 1,
    balance: 0,
    getGif: null
  },
  /**
   * 是否需要登录
   * 是否需要绑定手机号码
   */
  user_is_need_login(user) {
    // 用户信息是否正确
    if (user == false) {
      return true;
    }

    // 是否需要绑定手机号码
    if ((user.is_mandatory_bind_mobile || 0) == 1) {
      if ((user.mobile || null) == null) {
        return true;
      }
    }

    return false;
  },
  /**
   * 用户登录
   * object     回调操作对象
   * method     回调操作对象的函数
   * auth_data  授权数据
   */
  user_auth_login_getPhone(object, method, auth_data) {
    //console.log("user_auth_login_getPhone");
    var self = this;
    wx.checkSession({
      success: function () {
        var user = self.get_user_info(object, method); //self.get_user_cache_info();
        var openid = user.weixin_openid;
        if (openid != null) {
          self.get_user_phone_info(object, method, openid, auth_data);
        }
      },
      fail: function () {
        //console.log("user_auth_login_getPhone fail");
        self.user_login(object, method);
      }
    });
  },
  /**
   * 获取用户授权信息
   * object     回调操作对象
   * method     回调操作对象的函数
   * openid     用户openid
   * auth_data  授权数据
   */
  get_user_phone_info(object, method, openid, auth_data) {
    //console.log("get_user_phone_info");
    // 邀请人参数
    // var params = wx.getStorageSync(this.data.cache_launch_info_key) || null;
    // var referrer = (params == null) ? 0 : (params.referrer || 0);

    // 远程解密数据
    wx.showLoading({
      title: "授权中..."
    });
    var self = this;
    wx.request({
      url: self.get_request_url('WechatUserPhoneAuth', 'user'),
      method: 'POST',
      data: {
        "encrypted_data": auth_data.encryptedData,
        "iv": auth_data.iv,
        "openid": openid,
      },
      dataType: 'json',
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: (res) => {
        wx.hideLoading();
        if (res.data.code == 0) {
          //console.log("phoneNumber:" + res.data.data);
          var user = wx.getStorageSync(this.data.cache_user_info_key);
          user.mobile = res.data.data;
          wx.setStorage({
            key: self.data.cache_user_info_key,
            data: user,
            success: (res) => {
              if (typeof object === 'object' && (method || null) != null) {
                object[method]();
              }
            },
            fail: () => {
              self.showToast('用户信息缓存失败');
            }
          });

        } else {
          self.showToast(res.data.msg);
        }
      },
      fail: () => {
        wx.hideLoading();
        self.showToast('服务器请求出错');
      },
    });
  },
  /**
   * 获取用户信息,信息不存在则唤醒授权
   * object     回调操作对象
   * method     回调操作对象的函数
   * return     有用户数据直接返回, 则回调调用者
   */
  get_user_info(object, method) {
    var user = this.get_user_cache_info();
    if (user == false) {
      // 唤醒用户授权
      // this.user_login(object, method);

      return false;
    } else {
      return user;
    }
  },
  /**
   * 用户登录
   * object     回调操作对象
   * method     回调操作对象的函数
   * auth_data  授权数据
   */
  user_auth_login(object, method, auth_data) {
    //console.log("user_auth_login");
    var self = this;
    wx.checkSession({
      success: function () {
        var openid = wx.getStorageSync(self.data.cache_user_login_key) || null;
        if (openid == null) {
          self.user_login(object, method);
        } else {
          self.get_user_login_info(object, method, openid, auth_data);
        }
      },
      fail: function () {
        self.user_login(object, method);
      }
    });
  },
  /**
   * 用户登录
   * object     回调操作对象
   * method     回调操作对象的函数
   * auth_data  授权数据
   */
  user_login(object, method) {
    //console.log("user_login");
    var openid = wx.getStorageSync(this.data.cache_user_login_key) || null;
    if (openid == null) {
      var self = this;
      // 加载loding
      wx.showLoading({
        title: "授权中..."
      });
      wx.login({
        success: (res) => {
          if (res.code) {
            wx.request({
              url: self.get_request_url('wechatuserauth', 'user'),
              method: 'POST',
              data: {
                authcode: res.code
              },
              dataType: 'json',
              header: {
                'content-type': 'application/x-www-form-urlencoded'
              },
              success: (res) => {
                wx.hideLoading();
                if (res.data.code == 0) {
                  var data = res.data.data;
                  if ((data.is_user_exist || 0) == 1) {
                    //console.log("is_user_exist");
                    wx.setStorage({
                      key: self.data.cache_user_info_key,
                      data: data,
                      success: (res) => {
                        if (typeof object === 'object' && (method || null) != null) {
                          object[method]();
                        }
                      },
                      fail: () => {
                        self.showToast('用户信息缓存失败');
                      }
                    });
                  } else {
                    wx.setStorage({
                      key: self.data.cache_user_login_key,
                      data: data.openid
                    });
                    self.login_to_auth();
                  }
                } else {
                  wx.hideLoading();
                  self.showToast(res.data.msg);
                }
              },
              fail: (e) => {
                wx.hideLoading();
                // self.showToast('服务器请求出错');
                self.showToast(e);
              },
            });
          }
        },
        fail: (e) => {
          wx.hideLoading();
          self.showToast('授权失败');
        }
      });
    } else {
      this.login_to_auth();
    }
  },
  /**
   * 获取用户授权信息
   * object     回调操作对象
   * method     回调操作对象的函数
   * openid     用户openid
   * auth_data  授权数据
   */
  get_user_login_info(object, method, openid, auth_data) {
    //console.log("get_user_login_info");
    // 邀请人参数
    var params = wx.getStorageSync(this.data.cache_launch_info_key) || null;
    var referrer = (params == null) ? 0 : (params.referrer || 0);

    // 远程解密数据
    wx.showLoading({
      title: "授权中..."
    });
    var self = this;
    wx.request({
      url: self.get_request_url('wechatuserinfo', 'user'),
      method: 'POST',
      data: {
        "encrypted_data": auth_data.encryptedData,
        "iv": auth_data.iv,
        "openid": openid,
        "referrer": referrer
      },
      dataType: 'json',
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: (res) => {
        wx.hideLoading();
        // //console.log("res:" + res);
        if (res.data.code == 0) {

          wx.setStorage({
            key: self.data.cache_user_info_key,
            data: res.data.data,
            success: (res) => {
              if (typeof object === 'object' && (method || null) != null) {
                object[method]();

              }
            },
            fail: () => {
              self.showToast('用户信息缓存失败');
            }
          });
        } else {
          self.showToast(res.data.msg);
        }
      },
      fail: () => {
        wx.hideLoading();
        self.showToast('服务器请求出错');
      },
    });
  },
  get_request_url(a, c, plugins, params) {
    a = a || "index";
    c = c || "index";

    // 是否插件请求
    var plugins_params = "";
    if ((plugins || null) != null) {
      plugins_params = "&pluginsname=" + plugins + "&pluginscontrol=" + c + "&pluginsaction=" + a;

      // 走api统一插件调用控制器
      c = "plugins"
      a = "index"
    }

    // 参数处理
    params = params || "";
    if (params != "" && params.substr(0, 1) != "&") {
      params = "&" + params;
    }

    // 用户信息
    var user = this.get_user_cache_info();
    var token = (user == false) ? '' : user.token || '';
    return this.data.request_url +
      "index.php?s=/api/" + c + "/" + a + plugins_params +
      "&application=app&application_client_type=weixin" +
      "&token=" +
      token +
      "&ajax=ajax" +
      params;
  },
  /**
   * 从缓存获取用户信息
   */
  get_user_cache_info() {
    let user = wx.getStorageSync(this.data.cache_user_info_key) || null;
    if (user == null) {
      return false;
    }
    return user;
  },
  showToast(msg, status) {
    if ((status || 'error') == 'success') {
      wx.showToast({
        title: msg,
        duration: 3000
      });
    } else {
      wx.showToast({
        // image: '/images/default-toast-error.png',
        icon: 'none',
        title: msg,
        duration: 5000
      });
    }
  }
})